﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using E4RPTools;

namespace E4RPManager.Controls
{
    public partial class LicenseGenerator : Form
    {
        public LicenseGenerator()
        {
            InitializeComponent();
            dateTimePicker.Value = DateTime.Now.AddMonths(6);
            productComboBox.Items.AddRange(ProductList());
            productComboBox.Sorted = true;
            generateButton.Click += GenerateButtonClick;
        }
        
        private static string[] ProductList()
        {
            var products = new List<string>();
            foreach (Product product in Enum.GetValues(typeof(Product)))
                products.Add(product.ToString());
            return products.ToArray();
        }

        private void ClearControlErrors()
        {
            errorProvider.SetError(infoTextBox, "");
            errorProvider.SetError(productComboBox, "");
            errorProvider.SetError(dateTimePicker, "");
        }

        private bool ValidateData()
        {
            if (infoTextBox.Text == String.Empty)
            {
                errorProvider.SetError(infoTextBox, "Indique a informação do computador a licenciar.");
                return false;
            }
            int info;
            if (!int.TryParse(infoTextBox.Text, out info))
            {
                errorProvider.SetError(infoTextBox, "Indique uma informação válida do computador a licenciar.");
                return false;
            }
            if (productComboBox.Text == String.Empty)
            {
                errorProvider.SetError(productComboBox, "Indique a produto a licenciar.");
                return false;
            }
            if (dateTimePicker.Value.Date < DateTime.Now.Date)
            {
                errorProvider.SetError(dateTimePicker, "Indique uma data limite válida a licenciar.");
                return false;
            }
            return true;
        }
        
        private static string CheckDigit(long value)
        {
            var stringValue = Math.Abs(value) + "00";
            double total = 0;
            for (var i = stringValue.Length; i > 0; i--)
            {
                var weight = Math.Pow(10, i - 1) % 97;                
                var indexValue = Convert.ToInt64(stringValue.Substring(stringValue.Length - i, 1));
                total += weight*indexValue;
            }                
            var result = 98 - (total % 97);
            return result.ToString();
        }


        private string BuildLicense()
        {
            var info = Convert.ToInt32(infoTextBox.Text);
            var productCode = (Product)Enum.Parse(typeof(Product), productComboBox.Text);
            var productVersion = Convert.ToInt64(productVersionSpinEdit.EditValue);
            var date = dateTimePicker.Value.Day.ToString().PadLeft(2, '0') + dateTimePicker.Value.Month.ToString().PadLeft(2, '0') + dateTimePicker.Value.Year;
            var value = Convert.ToInt64(date) + info + (long)productCode + productVersion;
            return date + value + CheckDigit(value);
        }

        void GenerateButtonClick(object sender, EventArgs e)
        {
            ClearControlErrors();
            if (!ValidateData()) return;
            licenseKeyTextBox.Text = BuildLicense();
        }

    }
}
